package org.holynite.fieldmanage.services

import org.holynite.fieldmanage.Utils.ManagementException
import org.holynite.fieldmanage.ejbs.ChargeManagement
import org.holynite.fieldmanage.entities.ChargeRule
import org.holynite.fieldmanage.entities.ChargeScheme
import org.holynite.fieldmanage.persistence.ChargeRuleEAO
import org.holynite.fieldmanage.persistence.ChargeSchemeEAO
import org.holynite.fieldmanage.types.Exceptions

import javax.ejb.EJB
import javax.ejb.Stateless

/**
 * Created by midnite on 15/1/25.
 */
@Stateless(name = "chargeControl", mappedName = "chargeControlBean")
class ChargeControlBean implements ChargeManagement {

	@EJB(beanName = "chargeSchemeEao")
	ChargeSchemeEAO csEao
	@EJB(beanName = "chargeRuleEao")
	ChargeRuleEAO crEao

	@Override
	void addScheme(ChargeScheme scheme) throws ManagementException {
		try {
			csEao.save(scheme)
		} catch (Exception e) {
			throw new ManagementException(Exceptions.ChargeScheme)
		}
	}

	@Override
	void saveScheme(ChargeScheme scheme) throws ManagementException {
		try {
			csEao.update(scheme)
		} catch (Exception e) {
			throw new ManagementException(Exceptions.ChargeScheme)
		}
	}

	@Override
	void removeScheme(String schemeId) throws ManagementException {
		try {
			crEao.removeAllRulesInScheme(schemeId)
			csEao.delete(ChargeScheme, schemeId)
		} catch (Exception e) {
			throw new ManagementException(Exceptions.ChargeScheme)
		}
	}

	@Override
	void removeRule(String schemeId, String ruleId) throws ManagementException {
		try {
			crEao.removeRuleInScheme(schemeId, ruleId)
		} catch (Exception e) {
			throw new ManagementException(Exceptions.ChargeRule)
		}
	}

	@Override
	void addRule(ChargeScheme scheme, ChargeRule rule) throws ManagementException {
		try {
			rule.schemeId = scheme.schemeId
			crEao.save(rule)
		} catch (Exception e) {
			throw new ManagementException(Exceptions.ChargeRule)
		}
	}

	@Override
	void saveRule(ChargeRule rule) throws ManagementException {
		try {
			crEao.update(rule)
		} catch (Exception e) {
			throw new ManagementException(Exceptions.ChargeRule)
		}
	}

	@Override
	List<ChargeScheme> findSchemes(String keyword) {
		csEao.searchScheme(keyword)
	}

	@Override
	ChargeScheme fetchSchemeById(String schemeId) {
		csEao.findScheme(schemeId)
	}

	@Override
	ChargeScheme fillScheme(ChargeScheme scheme) {
		LinkedHashSet<ChargeRule> rules = crEao.listAllRulesInScheme(scheme.schemeId)
		scheme.chargeRules = rules
		return scheme
	}

	@Override
	List<ChargeRule> searchRules(String scheme, String keyword) {
		crEao.searchRulesInScheme(scheme, keyword)
	}
}
